<?php

namespace Models;

class MembershipModel {
    
    protected $_connection;
    
    protected $_currentMember;
    
    public function __construct($connection) {
        $this->_connection = $connection;
    }
    
    public function add($member) {
        
        $salt = md5(time());
        $member['password'] = $this->_hashPassword($member['password'], $salt);
        $member['salt'] = $salt;
        
        $sth = $this->_connection->prepare(
            'INSERT INTO `members` ' .
            '(`login`,`email`,`password`,`salt`) values ' .
            '(:login,:email,:password,:salt)'
        );
        
        $sth->execute($member);
        
        return $this->_connection->lastInsertId();
    }
    
    public function login($login, $password) {
        
        $sth = $this->_connection->prepare(
            'SELECT `id`, `password`, `salt` ' . 
            'FROM `members`' .
            'WHERE `login` = ?'
        );
        
        $sth->setFetchMode(\PDO::FETCH_ASSOC);
        
        if ($sth->execute([$login])) {
            
            $res = $sth->fetch();
            if ($this->_validatePassword($password, $res['password'], $res['salt'])) {
                
                $this->_currentMember = [
                    'id'    => $res['id'],
                    'login' => $login                    
                ];
                
                return true;
            }
        }
        
        return false;
    }
    
    public function getCurrentMember() {
        return $this->_currentMember;
    }
    
    public function isExists($type, $value) {
        
        $allowedType = array_search($type, ['login', 'email']) !== -1;
        
        if (!$allowedType) {
            throw new Exception('Only the following types are allowed: login, email');
        }

        $sth = $this->_connection->prepare(
            "SELECT COUNT(1) as isEmpty FROM `members` WHERE `$type` = ?"
        );
        
        $sth->setFetchMode(\PDO::FETCH_ASSOC);
        
        if ($sth->execute([$value])) {
            $res = $sth->fetch();
            return $res['isEmpty'] > 0;
        }
        
        return false;
    }
    
    protected function _validatePassword($password, $storedPassword, $salt) {
        return $storedPassword === $this->_hashPassword($password, $salt);
    }
    
    protected function _hashPassword($password, $salt) {
        return md5($password . $salt);
    }
}